<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { NAvatar, NButton, NDivider, NForm, NFormItem, NInput, NModal, NPagination, NSpin } from 'naive-ui';
import { deleteFriend, fetchFriendInfo, getAllPendingFriends } from '@/service/api/friend';
import { fetchRecentGames } from '@/service/api/game';
import { useAuthStore } from '@/store/modules/auth';
import emitter from '@/utils/event-bus';

// 修改Friend类型为新接口结构
interface FriendPending {
  otherId: number;
  otherUsername: string;
  otherAvatar: string;
  otherEmail: string;
  createTime: string;
  statusCode: string;
  tag: string | null;
}

const friends = ref<FriendPending[]>([]);
const loading = ref(false);
const authStore = useAuthStore();

const searchForm = ref({
  name: '',
  email: ''
});

const filteredFriends = computed(() => {
  return friends.value.filter(friend => {
    return (
      (!searchForm.value.name || (friend.otherUsername && friend.otherUsername.includes(searchForm.value.name))) &&
      (!searchForm.value.email || (friend.otherEmail && friend.otherEmail.includes(searchForm.value.email)))
    );
  });
});

const showModal = ref(false);
const detailFriend = ref<any>(null);
const detailLoading = ref(false);
const recentGames = ref<any[]>([]);
const recentLoading = ref(false);
const deleteLoading = ref(false);
const deleteId = ref<number | null>(null);
const showDeleteModal = ref(false);

const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

async function handleCardClick(friend: FriendPending) {
  detailLoading.value = true;
  showModal.value = true;
  try {
    console.log('请求好友详情参数:', Number(authStore.userInfo.userId), friend.otherId);
    const res = (await fetchFriendInfo(Number(authStore.userInfo.userId), friend.otherId)) as any;
    console.log('好友详情接口返回:', res);
    const code = res.response?.data?.code;
    if (code === 200) {
      detailFriend.value = res.data;
      // 获取该好友最近游玩
      recentLoading.value = true;
      try {
        const recentRes = (await fetchRecentGames(friend.otherId.toString(), 5)) as any;
        if (recentRes.response?.data?.code === 200) {
          recentGames.value = recentRes.data || [];
        } else {
          recentGames.value = [];
        }
      } catch {
        recentGames.value = [];
      } finally {
        recentLoading.value = false;
      }
    } else {
      detailFriend.value = null;
      window.$message?.error(res.response?.data?.message || '获取好友详情失败');
      recentGames.value = [];
    }
  } finally {
    detailLoading.value = false;
  }
}

function handleCloseModal() {
  showModal.value = false;
}

function handleDeleteClick(friend: FriendPending) {
  deleteId.value = friend.otherId;
  showDeleteModal.value = true;
}

async function confirmDelete() {
  if (deleteId.value === null) return;
  deleteLoading.value = true;
  try {
    const friend = friends.value.find(f => Number(f.otherId) === Number(deleteId.value));
    if (!friend) return;
    const res = await deleteFriend(Number(authStore.userInfo.userId), friend.otherId);
    if (res && res.response?.data?.code === 200) {
      window.$message?.success('删除成功');
      await loadFriends();
    } else {
      window.$message?.error(res.response?.data?.message || '删除失败');
    }
  } catch (e) {
    window.$message?.error('删除失败');
  } finally {
    deleteLoading.value = false;
    showDeleteModal.value = false;
    deleteId.value = null;
  }
}

// 页面加载时获取好友列表
async function loadFriends(page = 1) {
  loading.value = true;
  try {
    const res = await getAllPendingFriends({
      userId: Number(authStore.userInfo.userId),
      pageNum: page,
      pageSize: pageSize.value,
      name: searchForm.value.name,
      email: searchForm.value.email
    });
    const code = res.response?.data?.code;
    if (code === 200) {
      const data = res.response?.data?.data;
      if (Array.isArray(data)) {
        friends.value = data;
        total.value = data.length;
      } else if (data && Array.isArray(data.list)) {
        friends.value = data.list;
        total.value = Number(data.total) || data.list.length;
      } else {
        friends.value = [];
        total.value = 0;
      }
    } else {
      friends.value = [];
      total.value = 0;
      window.$message?.error((res.response?.data && (res.response.data as any).message) || '获取好友列表失败');
    }
  } catch {
    console.error('获取好友列表异常:');
    window.$message?.error('获取好友列表失败');
  } finally {
    loading.value = false;
  }
}

function handlePageChange(page: number) {
  currentPage.value = page;
  loadFriends(page);
}

function handleSearch() {
  currentPage.value = 1;
  loadFriends(1);
}

function getCoverUrl(game) {
  if (game && game.pic) {
    const base = game.pic.endsWith('/') ? game.pic : `${game.pic}/`;
    return `${base}assets/main/game-logo.svg`;
  }
  return '/src/assets/imgs/game-logo.svg';
}

onMounted(() => {
  loadFriends();
  emitter.on('refresh-friend-list', () => loadFriends());
});
onUnmounted(() => {
  emitter.off('refresh-friend-list', () => loadFriends());
});
</script>

<template>
  <div class="friends-page">
    <div class="search-card">
      <NForm inline :model="searchForm" class="search-form">
        <NFormItem label="名称">
          <NInput v-model:value="searchForm.name" placeholder="请输入名称" clearable @input="handleSearch" />
        </NFormItem>
        <NFormItem label="邮箱">
          <NInput v-model:value="searchForm.email" placeholder="请输入邮箱" clearable @input="handleSearch" />
        </NFormItem>
      </NForm>
    </div>
    <div class="friends-list">
      <div v-for="friend in filteredFriends" :key="friend.otherId" class="friend-card" @click="handleCardClick(friend)">
        <NAvatar :size="56" class="friend-avatar" round>{{ friend.otherUsername?.charAt(0) }}</NAvatar>
        <div class="friend-info">
          <div class="friend-name">{{ friend.otherUsername }}</div>
          <div class="friend-email">{{ friend.otherEmail }}</div>
        </div>
        <NButton
          quaternary
          circle
          size="small"
          class="delete-btn"
          title="删除好友"
          @click.stop="handleDeleteClick(friend)"
        >
          🗑️
        </NButton>
      </div>
    </div>
    <NModal
      v-model:show="showModal"
      preset="dialog"
      style="max-width: 700px; max-height: 80vh; overflow: auto; border-radius: 16px"
      @close="handleCloseModal"
    >
      <template v-if="detailFriend">
        <div class="modal-header">
          <span class="modal-header-title">好友详情</span>
        </div>
        <div class="info-card">
          <div class="avatar-block">
            <NAvatar :size="80" round>{{ detailFriend.otherUsername?.charAt(0) }}</NAvatar>
            <div class="nickname">{{ detailFriend.otherUsername }}</div>
            <div class="email">{{ detailFriend.otherEmail }}</div>
          </div>
          <div class="info-list">
            <div>
              <b>分组：</b>
              {{ detailFriend.tag }}
            </div>
            <div>
              <b>添加时间：</b>
              {{ detailFriend.createTime ? detailFriend.createTime.split(' ')[0] : '' }}
            </div>
            <div>
              <b>状态：</b>
              {{ detailFriend.statusCode }}
            </div>
          </div>
        </div>
        <NDivider />
        <div class="section-title">
          <span>最近游玩</span>
        </div>
        <NSpin :show="recentLoading">
          <div v-if="recentGames.length > 0">
            <div v-for="game in recentGames" :key="game.id" class="game-card">
              <img :src="getCoverUrl(game)" :alt="game.gameName" class="game-cover" />
              <div class="game-info">
                <div class="game-title">{{ game.gameName }}</div>
                <div class="game-meta">类型：{{ game.gameCategory }}</div>
                <div class="game-meta">游戏时长：{{ game.playTime }}分钟</div>
                <div class="game-meta">最近游玩：{{ game.lastPlayed ? game.lastPlayed.split('T')[0] : '' }}</div>
              </div>
            </div>
          </div>
          <div v-else style="color: #999; text-align: center; padding: 20px">暂无最近游玩记录</div>
        </NSpin>
      </template>
      <template #action>
        <NButton type="primary" @click="handleCloseModal">关闭</NButton>
      </template>
    </NModal>
    <NModal v-model:show="showDeleteModal" preset="dialog" title="确认删除好友？">
      <div>删除后将无法恢复，确定要删除该好友吗？</div>
      <template #action>
        <NButton @click="showDeleteModal = false">取消</NButton>
        <NButton type="error" :loading="deleteLoading" @click="confirmDelete">确认删除</NButton>
      </template>
    </NModal>
    <NPagination
      v-model:page="currentPage"
      :page-size="pageSize"
      :item-count="total"
      style="margin: 32px auto 0; display: flex; justify-content: center"
      @update:page="handlePageChange"
    />
  </div>
</template>

<style scoped>
.friends-page {
  background: #f6f8fa;
  min-height: 100vh;
  padding: 32px 0 32px 32px;
}
.search-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px #0001;
  padding: 24px 32px;
  margin: 0 auto 32px auto;
  max-width: 900px;
}
.friends-list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 32px 16px;
  align-items: start;
  justify-items: start;
}
.friend-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px #0001;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  width: 250px;
  min-width: 250px;
  max-width: 250px;
  cursor: pointer;
  transition: box-shadow 0.2s;
  box-sizing: border-box;
  position: relative;
}
.friend-card:hover {
  box-shadow: 0 4px 16px #6a82fb33;
}
.friend-avatar {
  margin-right: 12px;
  background: linear-gradient(135deg, #6a82fb 0%, #fc5c7d 100%);
  color: #fff;
  font-size: 18px;
  flex-shrink: 0;
}
.friend-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
  min-width: 0;
  overflow: hidden;
}
.friend-name {
  font-size: 15px;
  font-weight: bold;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.friend-email {
  color: #888;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.modal-header {
  display: flex;
  align-items: center;
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border-radius: 16px 16px 0 0;
  padding: 20px 24px;
  color: #fff;
  margin-bottom: 16px;
}
.modal-header-icon {
  font-size: 28px;
  margin-right: 12px;
}
.modal-header-title {
  font-size: 22px;
  font-weight: bold;
}
.info-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #0001;
  padding: 24px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 32px;
}
.avatar-block {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 32px;
}
.nickname {
  font-size: 20px;
  font-weight: bold;
  margin-top: 8px;
}
.email {
  color: #888;
  font-size: 14px;
  margin-top: 4px;
}
.info-list {
  font-size: 15px;
  color: #333;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 24px 0 16px 0;
}
.section-title-icon {
  font-size: 22px;
  margin-right: 8px;
  color: var(--primary-color, #6a82fb);
}
.game-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #0001;
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  padding: 16px;
  gap: 20px;
}
.game-cover {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  background: #eee;
}
.game-info {
  flex: 1;
}
.game-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 6px;
}
.game-meta {
  color: #666;
  font-size: 14px;
  margin-bottom: 2px;
}
:deep(.n-modal) {
  border-radius: 16px !important;
  overflow: hidden;
}
.delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
}
@media (max-width: 768px) {
  .friends-page {
    padding: 16px 0 16px 12px;
  }
}
</style>
